﻿using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace Bootstrap.Security.Mvc.HealthChecks
{
    /// <summary>
    /// NETCore 运行时检查
    /// </summary>
    public class NetCoreRuntimeCheck : IHealthCheck
    {
        /// <summary>
        /// 异步检查方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            var psi = new ProcessStartInfo("dotnet", "--info");
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            var p = Process.Start(psi);
            p.WaitForExit(5000);

            var result = await p.StandardOutput.ReadToEndAsync();
            var data = new Dictionary<string, object>()
            {
                { "dotnet --info", result }
            };
            return await Task.FromResult(HealthCheckResult.Healthy("OK", data));
        }
    }
}
